import { store } from '@/config'
import type { EquipmentClassification, IndicatorInfo } from '@/types'

const useEquipmentStore = defineStore('equipmentStore', () => {
  const types = ref<{ key: string, value: string }[]>([])
  const definitions = shallowRef<EquipmentClassification[]>([])

  const indicatorList = shallowRef<IndicatorInfo[]>([])

  async function getIndicatorList(equipmentId: number | string) {
    const { data } = await equipmentInfoApi.getEquipmentDetailById(+equipmentId)
    if (data.pointId) {
      const { data: indicators } = await indicatorApi.loadPointList(data.pointId)
      indicatorList.value = indicators ?? []
    }
  }

  async function getTypes() {
    const { data } = await sysDictionaryEncoApi.queryList('SHE_BEI_LEI_XING')
    types.value = data.map(v => ({
      key: v.dicKey,
      value: v.dicValue,
    }))
    return data
  }

  async function getDefinitions(params: {
    typeKey: string
    equipmentId?: number
  }) {
    let data: EquipmentClassification[] = []
    if (params.equipmentId) {
      const res = await equipmentDefinitionInfoApi.getEquipmentInfoById(
        params.equipmentId,
      )
      data = res.data
    }
    else {
      const res = await equipmentDefinitionApi.getDefinitionInfoByTypeKey(
        params.typeKey,
      )
      data = res.data
    }
    // 后端返回的ID和paramter字段都可能为null
    // 皆不可信！！
    // 自己随机一个uuid来作为标识吧
    for (const item of data) {
      if (Array.isArray(item.list)) {
        for (const subItem of item.list) {
          subItem._uuid = uuid()
        }
      }
      else {
        item.list = []
      }
    }
    definitions.value = data
    return data
  }

  getTypes()

  return {
    types,
    getTypes,

    definitions,
    getDefinitions,

    indicatorList,
    getIndicatorList,
  }
})

export function useEquipmentStoreHook() {
  return useEquipmentStore(store)
}

export default useEquipmentStore
